﻿using Ardalis.Specification;
using AutoMapper;
using HuaweiCloud.Dotnet.Samples.Common;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Dtos;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Entities;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Specification;
using Volo.Abp.Guids;

namespace HuaweiCloud.Dotnet.Samples.ESports.Main.Service
{
    public class BindInfoService : IBindInfoService
    {
        private readonly IDeviceService _deviceService;
        private readonly IRepository<BindInfo> _repository;
        private readonly IMapper _mapper;
        private readonly IGuidGenerator _idGenerator;
        public BindInfoService(IDeviceService deviceService
            , IRepository<BindInfo> repository
            , IMapper mapper
            , IGuidGenerator idGenerator)
        {
            _deviceService = deviceService;
            _repository = repository;
            _mapper = mapper;
            _idGenerator = idGenerator;
        }
        public async Task BindAsync(CreateBindInfoDto info, CancellationToken token = default)
        {
            var device = await _deviceService.GetAsync(info.DeviceId);
            if (device == null)
                throw new InvalidDataException("Invalid Id");
            var bindInfo = await _repository.FirstOrDefaultAsync(new BindInfoSpecification(info.DeviceId));
            if (bindInfo == null)
            {
                var item = _mapper.Map<BindInfo>(info);
                item.Id = _idGenerator.Create();
                await _repository.AddAsync(item, token);
            }
            else
            {
                bindInfo.UserId = info.UserId;
                await _repository.UpdateAsync(bindInfo, token);
            }
        }

        public async Task UnbindAsync(DeleteBindInfoDto info, CancellationToken token = default)
        {
            var bindInfo = await _repository.FirstOrDefaultAsync(new BindInfoSpecification(info.DeviceId));
            if (bindInfo == null)
                return;
            else
            {
                bindInfo.UserId = null;
                await _repository.UpdateAsync(bindInfo, token);
            }
        }
    }
}
